package com.jecy.base.baseproject.base.service.impl;


import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.jecy.base.baseproject.base.service.TokenService;
import com.jecy.base.baseproject.base.token.Constant;
import com.jecy.base.baseproject.base.token.TokenMangager;
import com.jecy.base.baseproject.domain.User;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author huijun
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Value("${token_time}")
    private int tokenTime;

    @Override
    public String generateToken(User user) {
        Preconditions.checkNotNull(user);

        return genToken(user);

    }

    @Override
    public Map<String, String> generateLoginSuccessInfo(User user) {
        return ImmutableMap.of("token", genToken(user),
                "eb_u", user.getUsername() == null ? "" : user.getUsername(),
                "eb_p", user.getPassword() == null ? "" : user.getPassword());
    }

    private String genToken(User user) {
        String randomNo = String.valueOf(Math.random()).substring(2, 6);
        Map<String, Object> map = new HashMap<>();
        map.put(Constant.TOKEN_USER_ID, user.getId());
        map.put(Constant.TOKEN_GEN_TIME, System.currentTimeMillis());
        map.put(Constant.SYS_VERSION, "v1");
        map.put(Constant.RANDOM_NO, randomNo);
        String token =  TokenMangager.generateToken(map, DateUtils.addDays(new Date(),
                tokenTime));
        return token;

    }
}
